package com.game.components;

import com.almasb.fxgl.dsl.FXGL;
import com.almasb.fxgl.entity.component.Component;
import com.almasb.fxgl.input.UserAction;
import com.game.enums.Direction;
import javafx.scene.input.KeyCode;

/**
 * Copyright (C), 2021-2041, chenc 豫R7HQ53
 *
 * @author: chenc
 * Date:     2023/12/4 21:00
 * Description: 人物移动组件
 */
public class MoveComponent extends Component {

    private KeyCode up = KeyCode.UP;
    private KeyCode down = KeyCode.DOWN;
    private KeyCode left = KeyCode.LEFT;
    private KeyCode right = KeyCode.RIGHT;
    private int speed;

    public MoveComponent(int speed){
        this.speed = speed;
    }

    public MoveComponent(KeyCode up,KeyCode down,KeyCode left,KeyCode right,int speed){
        this.up = up;
        this.down = down;
        this.left = left;
        this.right = right;
        this.speed = speed;
    }
    /**
     * 是否移动
     */
    private boolean isMoving = false;
    /**
     * 移动方向
     */
    public Direction direction;
    @Override
    public void onAdded() {
        FXGL.getInput().addAction(new UserAction("Move Up") {
            @Override
            protected void onAction() {
                if(isMoving){
                    return;
                }
                isMoving = true;
                direction = Direction.UP;
                entity.translateY(-speed);
                entity.setRotation(0);
            }
        }, up);
        FXGL.getInput().addAction(new UserAction("Move Down") {
            @Override
            protected void onAction() {
                if(isMoving){
                    return;
                }
                isMoving = true;
                direction = Direction.DOWN;
                entity.translateY(speed);
                entity.setRotation(180);
            }
        }, down);
        FXGL.getInput().addAction(new UserAction("Move Left") {
            @Override
            protected void onAction() {
                if(isMoving){
                    return;
                }
                isMoving = true;
                direction = Direction.LEFT;
                entity.translateX(-speed);
                entity.setRotation(270);
            }
        }, left);
        FXGL.getInput().addAction(new UserAction("Move Right") {
            @Override
            protected void onAction() {
                if(isMoving){
                    return;
                }
                isMoving = true;
                direction = Direction.RIGHT;
                entity.translateX(speed);
                entity.setRotation(90);
            }
        }, right);
    }

    @Override
    public void onUpdate(double tpf) {
        isMoving = false;
    }

    public Direction getDirection(){
        return direction;
    }
}
